package com.itheima.controller;

import com.itheima.common.Code;
import com.itheima.common.MessageConstant;
import com.itheima.common.Result;
import com.itheima.domain.AddressBook;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ShangChuanHang
 * @createTime 2022/6/6 21:40
 * @description
 */

@RestController
@RequestMapping("/addressBook")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 功能描述: 新增地址
     *
     * @param addressBook
     * @return : com.itheima.common.Result
     */
    @PostMapping
    public Result saveAddress(@RequestBody AddressBook addressBook) {
        int row = addressService.saveAddress(addressBook);
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.ADDRESS_SAVE_ERROR);
        }
        return new Result(Code.OK, MessageConstant.ADDRESS_SAVE_SUCCESS);
    }

    /**
     * 功能描述:  根据当前登录用户，查询用户地址列表
     *
     * @return : com.itheima.common.Result
     */
    @GetMapping("/list")
    public Result list() {
        List<AddressBook> addressBookList = addressService.list();
        if (addressBookList == null) {
            addressBookList = new ArrayList<>();
        }
        return new Result(Code.OK, MessageConstant.ADDRESS_GET_SUCCESS, addressBookList);
    }

    /**
     * 功能描述: 修改用户默认地址
     *
     * @param addr
     * @return : com.itheima.common.Result
     */
    @PutMapping("/default")
    public Result defaultAddr(@RequestBody AddressBook addr) {
        System.out.println("接收到请求参数：" + addr.getId());
        //1.调用service获取业务处理之后的数据
        int row = addressService.defaultAddr(addr.getId());
        if (row < 1) {
            return new Result(Code.ERROR, MessageConstant.UPDATE_DEFAULT_ADDRESS_ERROR);
        }
        //2.封装返回结果
        return new Result(Code.OK, MessageConstant.UPDATE_DEFAULT_ADDRESS_SUCCESS);
    }

    /**
     * 功能描述:  查询用户默认地址
     *
     * @return : com.itheima.common.Result
     */
    @GetMapping("/default")
    public Result getDefaultAddr() {
        //1.调用Service获取业务处理数据
        AddressBook addressBook = addressService.getDefaultAddr();
        //2.封装返回结果
        if (addressBook == null) {
            return new Result(Code.ERROR, MessageConstant.ADDRESS_GET_ERROR);
        }
        return new Result(Code.OK, MessageConstant.ADDRESS_GET_SUCCESS, addressBook);
    }
}

